package com.yape.job.Quartz;


import com.yape.dao.CrawlerTaskMapper;
import com.yape.po.CrawlerTask;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
public class QuartzTaskScheduler {

    @Autowired
    private Scheduler scheduler;
    @Autowired
    private CrawlerTaskMapper crawlerTaskMapper;

    @PostConstruct
    public void scheduleAllTasks() throws Exception {
        List<CrawlerTask> tasks = crawlerTaskMapper.selectEnabledTasks();
        for (CrawlerTask task : tasks) {
            scheduleTask(task);
        }
    }

    public void scheduleTask(CrawlerTask task) throws Exception {
        JobDetail jobDetail = JobBuilder.newJob(CrawlerQuartzJob.class)
                .withIdentity(task.getTaskName(), "crawler")
                .usingJobData("taskId", task.getId())
                .build();

        CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(task.getCron());
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(task.getTaskName() + "Trigger", "crawler")
                .withSchedule(cronSchedule)
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }
}